<?php

safe_require('artefact', 'feedback');

/**
 * This classes is a replacement from the original BlockInstance class provided
 * by Mahara.
 */
class BlockInstance extends BlockInstanceBase {

    public function render_viewing() {
        safe_require('blocktype', $this->get('blocktype'));
        $classname = generate_class_name('blocktype', $this->get('blocktype'));
        try {
            $content = call_static_method($classname, 'render_instance', $this);
        }
        catch (ArtefactNotFoundException $e) {
            // Whoops - where did the image go? There is possibly a bug
            // somewhere else that meant that this blockinstance wasn't
            // told that the image was previously deleted. But the block
            // instance is not allowed to treat this as a failure
            log_debug('Artefact not found when rendering a block instance. '
                . 'There might be a bug with deleting artefacts of this type? '
                . 'Original error follows:');
            log_debug($e->getMessage());
            $content = '';
        }

        $smarty = smarty_core();
        $smarty->assign('id',     $this->get('id'));
        $smarty->assign('blocktype', $this->get('blocktype'));
        $title = call_static_method($classname, 'override_instance_title', $this);
        // hide the title if required and no content is present
        if (call_static_method($classname, 'hide_title_on_empty_content')
            && !trim($content)) {
            return;
        }
        $smarty->assign('title', $title ? $title : $this->get('title'));

        // If this block is for just one artefact, we set the title of the
        // block to be a link to view more information about that artefact
        $configdata = $this->get('configdata');
        if (!empty($configdata['artefactid'])) {
            $smarty->assign('viewartefacturl', get_config('wwwroot') . 'view/artefact.php?artefact='
                . $configdata['artefactid'] . '&view=' . $this->get('view'));
        }

        if (method_exists($classname, 'feed_url')) {
            $smarty->assign('feedlink', call_static_method($classname, 'feed_url', $this));
        }
        $footer = ArtefactTypeFeedback::build_footer($this);
        $content = $content . $footer;
        $smarty->assign('content', $content);

        $result = $smarty->fetch('view/blocktypecontainerviewing.tpl');
        return $result;
    }

    public function delete() {
        db_begin();
        ArtefactTypeFeedback::delete_feedbacks_onparent($this->get('id'));
        parent::delete();
        db_commit();
    }

    public function copy(View $view, View $template, &$artefactcopies) {
        $blocktypeclass = generate_class_name('blocktype', $this->get('blocktype'));

        $configdata = $this->get('configdata');
        if (isset($configdata['copytype'])) {
            $copytype = $configdata['copytype'];
        }
        else {
            $copytype = call_static_method($blocktypeclass, 'default_copy_type');
        }

        $viewowner = $view->ownership();
        $templateowner = $template->ownership();
        $sameowner = ($viewowner['type'] == $templateowner['type'] && $viewowner['id'] == $templateowner['id']);

        // Check to see if the block is allowed to be copied into the new View
        //
        // Note for later: this is Blockinstance->allowed_in_view. This
        // determines whether this blockinstance should be copied into a view.
        // This could be a different question from BlockType::allowed_in_view!
        // But for now they use the same method.
        if (!call_static_method($blocktypeclass, 'allowed_in_view', $view)) {
            return false;
        }
        if ($copytype == 'nocopy' && !$sameowner) {
            return false;
        }

        $newblock = new BlockInstance(0, array(
            'blocktype'  => $this->get('blocktype'),
            'title'      => $this->get('title'),
            'view'       => $view->get('id'),
            'column'     => $this->get('column'),
            'order'      => $this->get('order'),
        ));

        if ($sameowner || $copytype == 'reference') {
            $newblock->set('configdata', $configdata);

            $newblock->commit();
            //START CHANGE
            $this->copy_feedbacks($newblock);
            //END CHANGE
            return true;
        }
        $artefactids = get_column('view_artefact', 'artefact', 'block', $this->get('id'));
        if (!empty($artefactids)
            && $copytype == 'full') {
            // Copy artefacts & put the new artefact ids into the new block.
            // Artefacts may have children (defined using the parent column of the artefact table) and attachments (currently
            // only for blogposts).  If we copy an artefact we must copy all its descendents & attachments too.

            $descendants = artefact_get_descendants($artefactids);

            // We need the artefact instance before we can get its attachments
            $tocopy = array();
            $attachmentlists = array();
            foreach ($descendants as $d) {
                if (!isset($artefactcopies[$d])) {
                    $tocopy[$d] = artefact_instance_from_id($d);
                    // Get attachments.
                    $attachmentlists[$d] = $tocopy[$d]->attachment_id_list();
                    foreach ($attachmentlists[$d] as $a) {
                        if (!isset($artefactcopies[$a]) && !isset($tocopy[$a])) {
                            $tocopy[$a] = artefact_instance_from_id($a);
                        }
                    }
                }
            }

            // Copy all the artefacts we haven't copied yet
            foreach ($tocopy as $aid => $a) {
                // Save the id of the original artefact's parent
                $artefactcopies[$aid] = (object) array('oldid' => $aid, 'oldparent' => $a->get('parent'));
                if (!empty($attachmentlists[$aid])) {
                    $artefactcopies[$aid]->oldattachments = $attachmentlists[$aid];
                }
                $artefactcopies[$aid]->newid = $a->copy_for_new_owner($view->get('owner'), $view->get('group'), $view->get('institution'));
            }

            // Record new artefact ids in the new block
            if (isset($configdata['artefactid'])) {
                $configdata['artefactid'] = $artefactcopies[$configdata['artefactid']]->newid;
            }
            else {
                foreach ($configdata['artefactids'] as &$oldid) {
                    $oldid = $artefactcopies[$oldid]->newid;
                }
            }
        }
        else {
            $configdata = call_static_method($blocktypeclass, 'rewrite_blockinstance_config', $view, $configdata);
        }
        $newblock->set('configdata', $configdata);
        
        $newblock->commit();
        //START CHANGE
        $this->copy_feedbacks($newblock);
        //END CHANGE
        return true;
    }

    public function copy_feedbacks($newblock){
        $from = $this->get('id');
        $to = $newblock->get('id');
           
        //may not be executed if configuration does not allow it.
        ArtefactTypeFeedback::copy_feebaks($from, $to);
    }
}

?>
